<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['commodity:category:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handlePull"
          >拉取</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="name"
        label="分类名称"
        width="260"
      ></el-table-column>
      <!-- <el-table-column
        prop="showLevel"
        label="等级"
        width="200"
      ></el-table-column> -->
      <el-table-column prop="mallImgUrl" label="缩略图" width="200">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.mallImgUrl"
            fit="fill"
            style="width: 50px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          {{ scope.row.sort ? scope.row.sort : 0 }}
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSort(scope.row)"
            v-hasPermi="['company:category:changeSort']"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否在推荐页展示" prop="isRecommendPageShow ">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommendPageShow"
            :active-value="1"
            :inactive-value="0"
            @change="handleRecommendPage(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否在用户端展示" prop="isShowUserHome">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShowUserHome"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowUser(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否在pc端展示" prop="isShowPcHome">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShowPcHome"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowPc(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否在pc菜单" prop="isIndexPcMenu">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isIndexPcMenu"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowPcMenu(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['company:category:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['commodity:category:add']"
            >新增</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:category:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleRecommend(scope.row)"
            v-hasPermi="['commodity:category:isShowRecommend']"
            >推荐管理</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改排序 -->
    <el-dialog title="修改排序" :visible.sync="isSort" width="400px">
      <el-form
        :model="sortForm"
        ref="sort"
        :rules="sortRule"
        label-width="80px"
      >
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="sortForm.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSort">确 定</el-button>
        <el-button @click="isSort = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-if="isAdd">
          <el-col :span="24">
            <el-form-item label="上级分类" prop="pid">
              <treeselect
                v-model="form.pid"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择上级分类"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="form.name"
                :disabled="!isAdd"
                placeholder="请输入商品分类名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isAdd">
            <el-form-item label="是否用户端展示" prop="isShowUserHome">
              <el-radio-group v-model="form.isShowUserHome">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类缩略图" prop="mallImgUrl">
              <Image-Upload
                :value="form.mallImgUrl"
                :limit="1"
                @input="getImgUrlEdit"
              ></Image-Upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="content">
              <Editor v-model="form.content" :height="200"></Editor>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="分类条形图" prop="mallImgUrl">
              <Image-Upload
                :value="form.mallImgUrl"
                :limit="1"
                @input="getImgUrlEditTwo"
              ></Image-Upload>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 推荐管理 -->
    <el-dialog
      :title="title"
      :visible.sync="reOpen"
      width="600px"
      append-to-body
    >
      <el-form
        ref="reForm"
        :model="recommendForm"
        :rules="reRules"
        label-width="125px"
      >
        <el-form-item label="是否在推荐中展示" prop="isShowRecommend">
          <el-radio-group v-model="recommendForm.isShowRecommend">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类背景图" prop="recommendImg">
          <Image-Upload
            :value="recommendForm.recommendImg"
            :limit="1"
            @input="getImgUrl"
          ></Image-Upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="reOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 拉取 -->
    <el-dialog
      title="拉取分类"
      :visible.sync="pullOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="reForm" :model="pullForm" label-width="125px">
        <el-form-item label="本地分类">
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="false"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPull">确 定</el-button>
        <el-button @click="pullOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMallProductCategory,
  changeIndexPcMenu,
  changeShowUserHome,
  changeShowPcHome,
  changeSort,
  changeShowRecommend,
  showTreeProductCate,
  addAllProductCate,
} from "@/api/product/category";
import {
  addCategory,
  showAllCategoryPriList,
  deletePriCate,
  updateMallProductCategoryByPri,
  isShowRecommend,
} from "@/api/company/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Category",
  dicts: ["sys_normal_disable"],
  components: { Treeselect },
  data() {
    return {
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      pullForm: {},
      pullOpen: false,
      // 遮罩层

      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      //是否显示修改排序弹出层
      isSort: false,
      //修改排序
      sortForm: {
        sort: null,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      reOpen: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 推荐管理
      recommendForm: {},
      //排序校验
      sortRule: {
        sort: [
          {
            required: true,
            message: "请输入排序",
            trriger: "blur",
            type: "number",
          },
        ],
      },
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: "请输入分类名称",
            trriger: "blur",
          },
        ],
      },
      reRules: {},
      isAdd: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 提交拉取
    submitPull() {
      const cateList = this.getMenuAllCheckedKeys();
      const pushData = { isGift: 1, cateList };
      addAllProductCate(pushData).then((res) => {
        this.$modal.msgSuccess("拉取成功");
        this.pullOpen = false;
        this.getList();
      });
    },
    // 拉取弹窗
    handlePull() {
      this.pullOpen = true;
      this.getProductCateTree();
    },
    /** 查询菜单树结构 */
    getProductCateTree() {
      showTreeProductCate().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();

      const cate = this.$refs.menu.getCheckedNodes();
      let halfCheckedNodes = this.$refs.menu.getHalfCheckedNodes();
      cate.unshift.apply(cate, halfCheckedNodes);
      const sendCate = cate.map((v) => {
        const { id, parentId } = v;
        return { id, parentId };
      });
      return sendCate;
      // 半选中的菜单节点
      // let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      // return checkedKeys;
    },
    getImgUrl(e) {
      this.recommendForm.recommendImg = e;
    },

    /** 推荐管理 */
    handleRecommend(row) {
      this.resetRe();
      this.reOpen = true;
      this.recommendForm.id = row.id;
      this.recommendForm.isShowRecommend = row.isShowRecommend;
      this.recommendForm.recommendImg = row.recommendImg;
      this.title = "推荐管理";
    },
    getImgUrlEdit(e) {
      this.form.mallImgUrl = e;
    },
    // getImgUrlEditTwo(e) {
    //   this.form.mallImgUrl = e;
    // },
    //修改排序
    handleSort(row) {
      this.isSort = true;
      this.sortForm = {
        sort: row.sort ? row.sort : 0,
        id: row.id,
      };
    },
    //修改排序提交
    submitFormSort() {
      this.$refs["sort"].validate((valid) => {
        if (valid) {
          changeSort(this.sortForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isSort = false;
            this.getList();
          });
        }
      });
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      showAllCategoryPriList(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, "productCategoryId");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.productCategoryId,
        label: node.name,
        children: node.children,
      };
    },
    //是否在推荐页展示
    handleRecommendPage(row) {
      const { id, isRecommendPageShow } = row;
      let text = row.isRecommendPageShow == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "推荐页展示吗？")
        .then(() => {
          return isShowRecommend({ id, isRecommendPageShow });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isRecommendPageShow = row.isRecommendPageShow == 1 ? 0 : 1;
        });
    },
    //是否pc菜单
    handleShowPcMenu(row) {
      const { id, isIndexPcMenu } = row;

      let text = row.isIndexPcMenu == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "pc端菜单吗？")
        .then(() => {
          return changeIndexPcMenu({ id, isIndexPcMenu });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isIndexPcMenu = row.isIndexPcMenu == 1 ? 0 : 1;
        });
    },
    //是否再用户端展示开关
    handleShowUser(row) {
      const { id, isShowUserHome } = row;

      let text = row.isShowUserHome == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "用户端展示吗？")
        .then(function () {
          return changeShowUserHome({ id, isShowUserHome });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShowUserHome = row.isShowUserHome == 1 ? 0 : 1;
        });
    },
    //是否在pc端展示开关
    handleShowPc(row) {
      const { id, isShowPcHome } = row;

      let text = row.isShowPcHome == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "用户端展示吗？")
        .then(function () {
          return changeShowPcHome({ id, isShowPcHome });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShowPcHome = row.isShowPcHome == 1 ? 0 : 1;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    resetRe() {
      this.recommendForm = {
        isShowRecommend: 1,
      };
      this.resetForm("reForm");
    },
    // 表单重置
    reset() {
      this.form = {
        pid: 0,
        isShowUserHome: 1,
        isShowPcHome: 1,
        isIndexPcMenu: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.pid = row.id;
      }
      this.isAdd = true;
      this.open = true;
      this.title = "添加分类";
      showAllCategoryPriList().then((response) => {
        this.deptOptions = [];
        console.log(response);
        const menu = { productCategoryId: 0, name: "一级分类", children: [] };
        menu.children = this.handleTree(response.data, "productCategoryId");

        this.deptOptions.push(menu);
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { id } = row;
      this.reset();
      this.isAdd = false;
      getMallProductCategory(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分类";
      });
      // showAllCategoryPriList().then((response) => {
      //   this.deptOptions = this.handleTree(response.data, "productCategoryId");
      // });
    },
    /** 提交按钮 */
    submitForm1: function () {
      this.$refs["reForm"].validate((valid) => {
        if (valid) {
          changeShowRecommend(this.recommendForm).then((response) => {
            this.$modal.msgSuccess("设置成功");
            this.reOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form = {
            ...this.form,
            isGift: 1,
          };
          if (this.form.id != undefined) {
            updateMallProductCategoryByPri(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的数据项？')
        .then(function () {
          return deletePriCate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
};
</script>
